<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="工序名称" prop="dictProcessName">
        <el-select
          v-model="queryParams.dictProcessName"
          placeholder="请选择工序名称"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="dict, index in getIntDictOptions(DICT_TYPE.CRAFT_PROCESS_NAME)"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排产与否" prop="dictIsProduction">
        <el-select
          v-model="queryParams.dictIsProduction"
          placeholder="请选择排产与否"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="(dict, index) in getIntDictOptions(DICT_TYPE.DICT_IS_PRODUCTION)"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报工方式 " prop="dictReportWay">
        <el-select
          v-model="queryParams.dictReportWay"
          placeholder="请选择报工方式 "
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="(dict, index) in getIntDictOptions(DICT_TYPE.DICT_REPORT_WAY)"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="dictEnableStatus">
        <el-select
          v-model="queryParams.dictEnableStatus"
          placeholder="请选择状态"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="dict in getIntDictOptions('dict_enable_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="btnWrap">
      <div>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['config:craft-product-process:export']"
        >
          数据导出
        </el-button>
        <el-button
          type="primary"
          @click="openForm('create')"
          v-hasPermi="['config:craft-product-process:create']"
        >
          新增
        </el-button>
      </div>
      <div>
        <el-button
          type="primary"
          @click="openTableTitleSet"
        >
          表头设置
        </el-button>
      </div>
    </div>
    <el-table ref="multipleTableRef" border row-key="id" :tree-props="{ children: 'childrenList' }" :height="tableHeight" default-expand-all v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" />
      <el-table-column label="序号" align="center" prop="parentIndex" type="" />
      <el-table-column v-if="tableTitle.length" :min-width="tableTitle[1].width" :header-align="tableTitle[1].headerAlign" :align="tableTitle[1].align" :label="tableTitle[1].label" :prop="tableTitle[1].field" >
        <template #default="scope">
            <dict-tag v-if="tableTitle[1].dictType" :type="tableTitle[1].dictType" :value="scope.row[tableTitle[1].field]" />
            <span v-else>{{ scope.row[tableTitle[1].field] }}</span>
          </template>
      </el-table-column>
      <template v-for="(item, index) in tableTitle">
        <el-table-column v-if="item.isTable && ![0, 1].includes(index)" :key="index" :type="item.type" :min-width="item.width" :header-align="item.headerAlign" :align="item.align" :label="item.label" :prop="item.field" >
          <template #default="scope">
            <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
            <span v-else>{{ scope.row[item.field] }}</span>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" header-align="left" align="left" width="250" fixed="right">
        <template #default="scope">
          <el-button  
            type="primary"
            link
            @click="openForm('createChild', scope.row.id)"
            v-show="scope.row.dictReportWay === 20 && scope.row.childrenList"
            v-hasPermi="['config:craft-product-process:create']"
          >
            新增
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id, scope.row.isChildren)"
            v-hasPermi="['config:craft-product-process:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            :loading="deleteLoading"
            v-hasPermi="['config:craft-product-process:delete']"
          >
            删除
          </el-button>
          <el-button
            link
            type="primary"
            :loading="moveLoading"
            v-if="scope.row.isChildren && scope.row.length > 1 && scope.row.index !== scope.row.length - 1"
            @click="moveDown(scope.row)"
          >
            下移
          </el-button>
          <el-button
            link
            type="primary"
            :loading="moveLoading"
            v-if="scope.row.isChildren && scope.row.length > 1 && scope.row.index !== 0"
            @click="moveUp(scope.row)"
          >
            上移
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CraftProductProcessForm ref="formRef" @success="getList" />
  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 表头设置 -->
  <table-width-set ref="tableTitleSet" @refresh="getList" />
</template>

<script setup lang="ts" name="CraftProductProcess">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import download from '@/utils/download'
import * as CraftProductProcessApi from '@/api/config/craftProductProcess'
import CraftProductProcessForm from './CraftProductProcessForm.vue'
import type { CrudSchema } from '@/hooks/web/useCrudSchemas'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const tableTitle = ref<CrudSchema[]>([]) //表头
const queryParams = reactive({
  pageNo: 1,
  pageSize: 50,
  dictProcessName: undefined,
  dictIsProduction: undefined,
  dictReportWay: undefined,
  dictEnableStatus: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const deleteLoading = ref(false)
const moveLoading = ref(false)
const code = 'CraftProductProcess'  //表头名
const tableHeight = ref(0)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CraftProductProcessApi.getCraftProductProcessPage(queryParams)
    list.value = data.list.map((item, index) => {
      item.parentIndex = index + 1  //父元素序号
      if (item.childrenList.length) {
        item.childrenList.map((child, index) => {
          child.index = index,  //判断是否显示上移
          child.length = item.childrenList.length   //判断是否显示下移
          return child
        })
      }
      return item
    })
    tableTitle.value = data.labels
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 打开表头设置
const tableTitleSet = ref()
const openTableTitleSet = () => {
  tableTitleSet.value.open(tableTitle.value, code)
}

// 上移
const moveUp = async (data) => {
  moveLoading.value = true
  try {
    await CraftProductProcessApi.moveUpCraftProductProcess(data.id, data.parentId)
    message.success('操作成功')
    getList()
  } finally {
    moveLoading.value = false
  }
}

// 下移
const moveDown = async (data) => {
  moveLoading.value = true
  try {
    await CraftProductProcessApi.moveDownCraftProductProcess(data.id, data.parentId)
    message.success('操作成功')
    getList()
  } finally {
    moveLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number, isChildren?: boolean) => {
  formRef.value.open(type, id, isChildren)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  deleteLoading.value = true
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CraftProductProcessApi.deleteCraftProductProcess(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } finally {
    deleteLoading.value = false
  }
}

// 多选
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

/** 导出按钮操作 */
const exportRef = ref()
const handleExport = () => {
  exportRef.value.open()
}

// 下载
const multipleTableRef = ref()
const downloadFun = async () => {
  const val = exportRef.value.params
  const params = {
    fileName: val.name,
    ids: []
  }
  if (val.range === 'all') {
    params.ids = []
  } else {
    params.ids = multipleSelection.value.map((item) => {
      return item['id']
    })
  }
  const data = await CraftProductProcessApi.exportCraftProductProcess(params)
  download.excel(data, val.name)
  multipleTableRef.value!.clearSelection()
}

/** 初始化 **/
onMounted(() => {
  const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
  tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 115
  getList()
})
</script>
<style lang="scss" scoped>
.btnWrap {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>
